package com.atguyigu.codesday02;


                          //      synchronized  版本的


       /*需求:有一个初始值为零的变量，现有两个线程对该变量操作,实现一个线程对变量加1，实现一个线程对变量减1,交替来10次
          1 高内聚低耦合的前提下，线程   操作 资源类
         2 判断、干活、通知
         3 防止线程的虚假唤醒，判断推荐使用while而不是单单的if判断  */

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class AirCondition3 {
    int number = 0;
   Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();


    public synchronized void increment() throws Exception {
        lock.lock();
        try {// 1判断
            while (number != 0) {
                condition.await();
            }
            //干活
            System.out.println(Thread.currentThread().getName() + "\t" + (++number));
            //3通知
           condition.signal();
        } finally {
            lock.unlock();
        }
    }

    public synchronized void decrement() throws Exception {
        lock.lock();
        try {  // 1判断
            while (number == 0) {
                condition.await();
            }
            //干活
            System.out.println(Thread.currentThread().getName() + "\t" + (--number));
            //3通知
            this.notifyAll();
        }finally {
            condition.signal();
        }
    }
}


public class ProdConsumerDemo3 {

    public static void main(String[] args) {

        AirCondition airCondition = new AirCondition();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    airCondition.increment();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },"A").start();


        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    airCondition.decrement();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },"B").start();


        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    airCondition.increment();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },"c").start();

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    airCondition.decrement();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        },"D").start();
    }
}
